import { routerMap } from '@/router/async/router.map'
import { isUrl } from '@/utils/util'
import store from '@/store'



/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerList
 * @param parent
 * @returns {*}
 */
function generator(routerList, parent) {
  return routerList.map(item => {
    const { title, keepAlive, hideChildrenInMenu, hiddenHeaderContent, funcList, icon, hidden, param1 } = item || {}
    let params = {}
    if (param1) {
      //自定义参数1为请求参数，不为空时传入
      try {
        params = JSON.parse(param1);
      } catch (e) {
        console.log(new Error("param1路由参数必须是json格式" + param1));
      }
    }
    const currentRouter = {
      // 路由名称，建议唯一
      name: item.key || item.name || '',
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component || item.key],
    }
    if (routerMap[item.component || item.name]) {
      // 该路由对应页面的 组件 :方案2 (动态加载)
      currentRouter.component = (routerMap[item.component || item.name])
    }
    // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
    let path = item.path || `${parent && parent.path || ''}/${item.key}`
    // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
    let meta = {
      title: title,
      icon: icon || undefined,
      hiddenHeaderContent: hiddenHeaderContent,
      keepAlive: keepAlive,
      funcList: funcList,
      authority: '*',
      invisible: hidden,
      routerId: item.routerId
    }
    if (item.otherUrl && isUrl(item.otherUrl)) {
      if (item.component) {
        params.otherUrl = encodeURIComponent(item.otherUrl)
      } else {
        delete currentRouter.component
        meta.link = item.otherUrl
      }
    }
    let page = {}
    page.title = title
    meta.page = page
    meta.query = params
    currentRouter.path = path
    currentRouter.meta = meta
    // 是否设置了隐藏菜单
    currentRouter.hidden = hidden

    // 是否设置了隐藏子菜单
    currentRouter.hideChildrenInMenu = hideChildrenInMenu

    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向: 这里更改重定向至工作台页面
    if (item.redirect) {
      currentRouter.redirect = "/workCenter/workplace"
    }
    // item.redirect && (currentRouter.redirect = item.redirect)

    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}

/**
 * 从路由 path 解析 i18n key
 * @param path
 * @returns {*}
 */
function getI18nKey(path) {
  const keys = path.split('/').filter(item => !item.startsWith(':') && item != '')
  keys.push('name')
  return keys.join('.')
}

export { generator, getI18nKey }
